import { allRoutes, constRoutes } from '@/route/allRoutes'
import { useUserStore } from '@/stores/userStore'
import pinia from '@/stores'

const userStore = useUserStore(pinia)
// 用户拥有的路由
const permissionString = userStore.permissions as string

const permissions: string[] = permissionString ? permissionString.split(',') : []
// 根据返回的用户权限，过滤出用户拥有的路由
const filterRoute = (all, permission: string[]) => {
  return all.filter((item) => {
    if (permission.includes(item.name)) {
      if (item.children && item.children.length > 1) {
        item.children = filterRoute(item.children, permission)
      }
      return true
    }
  })
}
// 深拷贝
// function deepClone(obj = {}) {
//   if (typeof obj !== 'object' || obj === null) return { obj }
//   let result
//
//   if (obj instanceof Array) {
//     result = []
//   } else {
//     result = {}
//   }
//
//   for (let key in obj) {
//     result[key] = obj[key]
//   }
//   return result
// }

// 计算用户路由
let userRoutes = constRoutes
if (permissions.length >= 1) {
  let permissionRoutes = []
  permissionRoutes = filterRoute(allRoutes, permissions)
  userRoutes = [...constRoutes, ...permissionRoutes]
}
export const routes = userRoutes
